using System;
using System.IO;
using System.Text;

namespace ThalesHsmComms
{
	public class GenerateCVVMsg : WSMMsg
	{
		public String Cvv{private set;get;}		
		private String cvk;
		private String pan;
		private String serviceCode;
		private String expiryDate;

		public GenerateCVVMsg (String cvk, String pan, String expiry_date, String service_code = "")
			:base("CW")
		{	
			this.cvk = cvk;
			this.pan = pan;
			this.expiryDate = expiry_date;
			if(service_code == null || service_code == string.Empty) 
			{
				throw new ArgumentNullException("Service Code must be specified.");
			}

			if(service_code.Length != 3)
			{
				throw new Exception("Service code MUST be 3 digits");
			}

			this.serviceCode = service_code;

		}

		override protected void Encode() 
		{
			
			StringBuilder data = new StringBuilder();
			
			try {
				
				// pack command code
				data.Append(this.commandCode);
				
				// pack source zpk
				data.Append(this.cvk);
				
				// pack pan
				data.Append(this.pan);
				
				// pack delimiter
				data.Append(";");
				
				// pack expiry date
				data.Append(this.expiryDate);
				
				// pack service code
				data.Append(this.serviceCode);
				
				this.requestData = Encoding.ASCII.GetBytes(data.ToString());
				
			} 
			catch (IOException ex)
			{
				Console.WriteLine(ex);
			}
		}

		override protected void Decode() 
		{
			// get cvv
			this.Cvv = this.GetNextBytesFromResponse(3);
		}
	}
}

